package com.lej.core.utils.extention

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken

inline fun <reified T> String.fromJson() = runCatching<T> {
    Gson().fromJson(this, object : TypeToken<T>() {}.type)
}.onFailure { this.logI("Gson");it.printStackTrace() }.getOrNull()

inline fun <reified T> JsonObject.fromJsonObject() = runCatching<T> {
    Gson().fromJson(this, object : TypeToken<T>() {}.type)
}.onFailure { toString().logI("Gson");it.printStackTrace() }.getOrNull()


fun Any.toJson(): String = Gson().toJson(this)

fun jsonObjectOf(vararg pairs: Pair<String, Any?>) = JsonObject().apply {
    pairs.forEach {
        it.second.let { value ->
            when (value) {
                is String -> addProperty(it.first, value)
                is Boolean -> addProperty(it.first, value)
                is Number -> addProperty(it.first, value)
                is Char -> addProperty(it.first, value)
                is JsonElement -> add(it.first, value)
            }
        }
    }
}
